/* 
 * CS:APP Data Lab 
 * 
 * <Please put your name and userid here>
 * 
 * bits.c - Source file with your solutions to the Lab.
 *          This is the file you will hand in to your instructor.
 *
 * WARNING: Do not include the <stdio.h> header; it confuses the dlc
 * compiler. You can still use printf for debugging without including
 * <stdio.h>, although you might get a compiler warning. In general,
 * it's not good practice to ignore compiler warnings, but in this
 * case it's OK.  
 */

 #if 0
 /*
  * Instructions to Students:
  *
  * STEP 1: Read the following instructions carefully.
  */
 
 You will provide your solution to the Data Lab by
 editing the collection of functions in this source file.
 
 INTEGER CODING RULES:
  
   Replace the "return" statement in each function with one
   or more lines of C code that implements the function. Your code 
   must conform to the following style:
  
   int Funct(arg1, arg2, ...) {
       /* brief description of how your implementation works */
       int var1 = Expr1;
       ...
       int varM = ExprM;
 
       varJ = ExprJ;
       ...
       varN = ExprN;
       return ExprR;
   }
 
   Each "Expr" is an expression using ONLY the following:
   1. Integer constants 0 through 255 (0xFF), inclusive. You are
       not allowed to use big constants such as 0xffffffff.
   2. Function arguments and local variables (no global variables).
   3. Unary integer operations ! ~
   4. Binary integer operations & ^ | + << >>
     
   Some of the problems restrict the set of allowed operators even further.
   Each "Expr" may consist of multiple operators. You are not restricted to
   one operator per line.
 
   You are expressly forbidden to:
   1. Use any control constructs such as if, do, while, for, switch, etc.
   2. Define or use any macros.
   3. Define any additional functions in this file.
   4. Call any functions.
   5. Use any other operations, such as &&, ||, -, or ?:
   6. Use any form of casting.
   7. Use any data type other than int.  This implies that you
      cannot use arrays, structs, or unions.
 
  
   You may assume that your machine:
   1. Uses 2s complement, 32-bit representations of integers.
   2. Performs right shifts arithmetically.
   3. Has unpredictable behavior when shifting an integer by more
      than the word size.
 
 EXAMPLES OF ACCEPTABLE CODING STYLE:
   /*
    * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
    */
   int pow2plus1(int x) {
      /* exploit ability of shifts to compute powers of 2 */
      return (1 << x) + 1;
   }
 
   /*
    * pow2plus4 - returns 2^x + 4, where 0 <= x <= 31
    */
   int pow2plus4(int x) {
      /* exploit ability of shifts to compute powers of 2 */
      int result = (1 << x);
      result += 4;
      return result;
   }
 
 FLOATING POINT CODING RULES
 
 For the problems that require you to implent floating-point operations,
 the coding rules are less strict.  You are allowed to use looping and
 conditional control.  You are allowed to use both ints and unsigneds.
 You can use arbitrary integer and unsigned constants.
 
 You are expressly forbidden to:
   1. Define or use any macros.
   2. Define any additional functions in this file.
   3. Call any functions.
   4. Use any form of casting.
   5. Use any data type other than int or unsigned.  This means that you
      cannot use arrays, structs, or unions.
   6. Use any floating point data types, operations, or constants.
 
 
 NOTES:
   1. Use the dlc (data lab checker) compiler (described in the handout) to 
      check the legality of your solutions.
   2. Each function has a maximum number of operators (! ~ & ^ | + << >>)
      that you are allowed to use for your implementation of the function. 
      The max operator count is checked by dlc. Note that '=' is not 
      counted; you may use as many of these as you want without penalty.
   3. Use the btest test harness to check your functions for correctness.
   4. Use the BDD checker to formally verify your functions
   5. The maximum number of ops for each function is given in the
      header comment for each function. If there are any inconsistencies 
      between the maximum ops in the writeup and in this file, consider
      this file the authoritative source.
 
 /*
  * STEP 2: Modify the following functions according the coding rules.
  * 
  *   IMPORTANT. TO AVOID GRADING SURPRISES:
  *   1. Use the dlc compiler to check that your solutions conform
  *      to the coding rules.
  *   2. Use the BDD checker to formally verify that your solutions produce 
  *      the correct answers.
  */
 
 
 #endif
 /* 
  * isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
  *   Example: isAsciiDigit(0x35) = 1.
  *            isAsciiDigit(0x3a) = 0.
  *            isAsciiDigit(0x05) = 0.
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 15
  *   Rating: 3
  */
 int isAsciiDigit(int x) {
  /*若x为0x30~0x39,则test1,test2的符号位相同，且为1。若溢出，则test1,test2的符号位相同，且为0。*/
  int test1=x+(~(0x30)+1);
  int test2=(~x+1)+0x39;//若溢出，二者的符号位仍是不同的，可排除。
  test1=(test1>>31)+1;
  test2=(test2>>31)+1;
  return test1&test2;
  //符号要求情况应该为二者都为1即1&1;其余情况均为0
}

 /* 
  * anyEvenBit - return 1 if any even-numbered bit in word set to 1
  *   Examples anyEvenBit(0xA) = 0, anyEvenBit(0xE) = 1
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 12
  *   Rating: 2
  */
 int anyEvenBit(int x) {
  /*对X的每个byte都进行 | 运算，只要有一个even-bit 为1，则&0x55结果不为0。 !!运算后可转换为1 */

  int test1=((x>>8)|(x>>16)|(x>>24)|x)&0x55;//even-bit 全为0时, test1=0, 否则不为0.

  return !!test1;     //将test通过!!运算转化为0或1的结果返回
}

 /* 
  * copyLSB - set all bits of result to least significant bit of x
  *   Example: copyLSB(5) = 0xFFFFFFFF, copyLSB(6) = 0x00000000
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 5
  *   Rating: 2
  */
 int copyLSB(int x) {
  /*使用掩码0x01 获得x的最低位，通过左移到最高为, 进行算术右移,变为由32个符号位组成的int数据*/
  int test1=x&1;//获得least-bit;
  x=(test1<<31)>>31;//将least-bit变为符号位，再使用算术右移, 补符号位(least-bit);
  return x;
}

 /* 
  * leastBitPos - return a mask that marks the position of the
  *               least significant 1 bit. If x == 0, return 0
  *   Example: leastBitPos(96) = 0x20
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 6
  *   Rating: 2 
  */
 int leastBitPos(int x) {
  /*~x在0~目标位为1，在目标位为0. ~x+1后0~目标位保持不变，而其他位为原值的反
  故 (~x+1)&x保留了0~目标位,而目标位~31都为0*/
  x=(~x+1)&x;
  return x;
}

 /* 
  * divpwr2 - Compute x/(2^n), for 0 <= n <= 30
  *  Round toward zero
  *   Examples: divpwr2(15,1) = 7, divpwr2(-33,4) = -2
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 15
  *   Rating: 2
  */
/**
 * divpwr2 - 通过位操作实现将一个整数除以2的n次幂。
 * 此函数的目的是在不使用乘法或除法运算符的情况下，通过位移操作计算x除以2的n次幂的结果。
 * 它通过首先确定x的符号位，然后使用位掩码调整x的值，最后执行右位移操作来完成。
 * 
 * 返回值: x除以2的n次幂的结果，以整数形式返回。
 */
int divpwr2(int x, int n) {
    // 定义符号位变量和临时变量，初始化为0。
    int sign = 0, var = 0;
    
    // 提取x的符号位：如果x为负，则sign为1；如果x为正，则sign为0。
    sign = x >> 31;
    
    // 计算一个掩码，该掩码用于调整负数的值，以确保在右移时不会引入额外的符号位。
    var = (1 << n) + (~0);
    
    // 根据x的符号位和计算出的掩码调整x的值，然后执行右位移操作，实现除以2的n次幂。
    return (x + (sign & var)) >> n;
}
 /*
  * bitCount - returns count of number of 1's in word
  *   Examples: bitCount(5) = 2, bitCount(7) = 3
  *   Legal ops: ! ~ & ^ | + << >>
  *   Max ops: 40
  *   Rating: 4
  */
int bitCount(int x)
{
  /*为了统计为1的位数,我们必须把这个32-bit的数值,转化为一个统计1个数的数字*/
  int test1 = (0x55 << 8) | (0x55);
  test1 = (test1 << 16) | (test1);
  x = (x & test1) + ((x >> 1) & test1); // 首先将每两位看成一个整体，利用掩码0101...0101计算每两位中1的个数，并存入x的对应位置
  // 例一个16-bit的数:10 11 00 11 11 00 01 10 -->> 01 10 00 10 10 00 01 01
  test1 = (0x33 << 8) | (0x33);
  test1 = (test1 << 16) | (test1);
  x = (x & test1) + ((x >> 2) & test1); /*再将每四位看成一个整体, 利用掩码0011...0011将每两位的1的个数变为
              每四位的1的个数，存入x的对应位置*/
  // 0110 0010 1000 0101 -->> 0011 0010 0010 0010
  test1 = (0x0f << 8) | (0x0f);
  test1 = (test1 << 16) | (test1);
  x = (x & test1) + ((x >> 4) & test1); /*再将每八位看成一个整体, 利用掩码0000 1111...0000 1111将每4位的1的个数变为
              每8位的1的个数，存入x的对应位置*/
  // 0011 0010 0010 0010 -->> 0000 0101 0000 0100
  test1 = (0xff << 16) | (0xff);
  x = (x & test1) + ((x >> 8) & test1); /*再将每16位看成一个整体, 利用掩码 0000 0000 1111 1111 0000 0000 1111 1111将每8位的1的个数变为
              每16位的1的个数，存入x的对应位置*/
  // 0000 0101 0000 0100 -->> 0000 0000 0000 1001 = (9)与原数吻合
  test1 = (0xff << 8) | (0xff);
  x = (x & test1) + ((x >> 16) & test1); /*再将这32位看成一个整体, 利用掩码 0000 0000 0000 0000 1111 1111 1111 1111将每16位的1的个数变为
                                          每32位的1的个数，存入x的对应位置*/
                                         // 此时x的数值就变为了原x中所有1的个数
  return x;
}
